<template>
  <div>
    <el-form :model="userInfo" ref="userInfoForm" label-width="80px">
      <el-form-item label="账号">
        <el-input v-model="userInfo.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户名">
        <el-input v-model="userInfo.nickname"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input type="password" v-model="passwordForm.newPassword"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          type="password"
          v-model="passwordForm.confirmPassword"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="confirmChangePassword"
          >修改密码</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { changeUserinfoApi } from "@/utils/api.js";

const userInfo = ref({
  username: localStorage.getItem("username"),
  nickname: localStorage.getItem("nickname"),
});

const id = localStorage.getItem("id");

const passwordForm = ref({
  newPassword: "",
  confirmPassword: "",
});

const confirmChangePassword = () => {
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    ElMessage.error("两次输入的密码不一致");
    return;
  }
  ElMessageBox.confirm("确认修改密码吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      changePassword();
    })
    .catch(() => {});
};

const changePassword = () => {
  const data = {
    id: id,
    // 如果有新的昵称，则使用新的昵称，否则使用原来的昵称
    nickname:
      userInfo.value.nickname !== localStorage.getItem("nickname")
        ? userInfo.value.nickname
        : localStorage.getItem("nickname"),
    // 如果有新的密码，则使用新的密码，否则使用空字符串，表示不修改密码
    newPassword:
      passwordForm.value.newPassword !== ""
        ? passwordForm.value.newPassword
        : "",
  };

  changeUserinfoApi(data)
    .then((response) => {
      if (response.data.code === 200) {
        ElMessage.success(response.data.msg);
        // 如果修改了昵称，则更新本地存储的昵称
        if (data.nickname !== localStorage.getItem("nickname")) {
          localStorage.setItem("nickname", data.nickname);
          window.location.reload();
        }
      } else {
        ElMessage.error(response.data.msg);
      }
    })
    .catch((error) => {
      ElMessage.error("修改密码失败：" + error);
    });
};
</script>

<style scoped>
/* 样式 */
</style>
